<template>
  <div class="role-power-box">
    <el-tree
      :data="menuList"
      ref="tree"
      show-checkbox
      v-bind="$attrs"
      node-key="menuId"
      :default-expanded-keys="defaultKeys"
      :default-checked-keys="defaultKeys"
      @check="handleClick"
      :props="defaultProps"
    >
    </el-tree>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { treeToArray } from "@/libs/util";
export default {
  name: "RolePower",
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "name"
      },
      checkedNodeKeys: [],
      defaultKeys: []
    };
  },
  computed: {
    ...mapState({
      menuList: (state) => state.login.menuList
    })
  },
  watch: {
    $attrs: {
      handler(val) {
        if (val.value) {
          let nodeKeys = val.value;
          let menu = treeToArray(this.menuList);
          let filters = menu
            .filter((x) => nodeKeys.some((y) => x.menuId == y))
            .filter((x) => !x.children);
          this.defaultKeys = filters.map((x) => x.menuId);
        }
      }
    }
  },
  methods: {
    handleClick(checkedNodes, checkedKeys) {
      this.checkedNodeKeys = checkedKeys.checkedKeys;
      // console.log('checkedNodeKeys', this.checkedNodeKeys)
      let nodeKeys = this.$refs.tree.getCheckedKeys();
      let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
      let checkedNodeKeys = [...nodeKeys, ...halfCheckedKeys];
      this.$emit("input", checkedNodeKeys);
    }
  }
};
</script>

<style scoped>
.role-power-box {
  height: 360px;
  overflow: auto;
}
.role-power-box >>> .el-tree-node__content {
  height: 32px;
}
</style>
